package hyj.qx.websocket.service.impl;

import hyj.qx.websocket.entity.Content;
import hyj.qx.websocket.mapper.ContentMapper;
import hyj.qx.websocket.mapper.UserMapper;
import hyj.qx.websocket.service.ContentService;
import hyj.qx.websocket.vo.ContentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Integer addContent(String username, String toUserName, String content) {
        Integer toId =userMapper.getIdByName(toUserName);
        Integer fromId =userMapper.getIdByName(username);
        System.out.println(toId+"and"+fromId);
        Content con = new Content();
        con.setToId(toId);
        con.setFromId(fromId);
        con.setContent(content);
        contentMapper.insert(con);
        return null;
    }

    @Override
    public List<ContentVo> selectContent(String fromName, String toName) {
        Integer fromId =userMapper.getIdByName(fromName);
        Integer toId = userMapper.getIdByName(toName);
       List<Content> contents= contentMapper.getContents(fromId,toId);

        List<ContentVo> contentVos = new ArrayList<>();
       for(Content content:contents){
           ContentVo contentVo =new ContentVo();
           if(content.getFromId() == fromId){
               contentVo.setContent(content.getContent());
               contentVo.setCreateTime(content.getCreateTime());
               contentVo.setFromName(fromName);
               contentVo.setToName(toName);
               contentVos.add(contentVo);
           }else {
               contentVo.setContent(content.getContent());
               contentVo.setCreateTime(content.getCreateTime());
               contentVo.setFromName(toName);
               contentVo.setToName(fromName);
               contentVos.add(contentVo);
           }
       }
       return contentVos;
    }
}
